//
//  HomeViewController+IM.m
//  Keping
//
//  Created by 23 on 2017/12/8.
//  Copyright © 2017年 柯平. All rights reserved.
//

#import "HomeViewController+IM.h"
#import "GPDeviceManager.h"
#import "GPMessageItem.h"
#import "GPChatDBTool.h"
#import "GPProfileItem.h"

@interface HomeViewController () <EMCallManagerDelegate, EMClientDelegate, EMChatManagerDelegate>

@end

@implementation HomeViewController (IM)

- (void)setupIMRealtime
{
    //注册实时通话回调
    [[EMClient sharedClient] addDelegate:self delegateQueue:nil];
    [[EMClient sharedClient].chatManager addDelegate:self delegateQueue:nil];
}


#pragma mark - EMClientDelegate
/**SDK连接服务器的状态变化时会接收到该回调*/
- (void)connectionStateDidChange:(EMConnectionState)aConnectionState
{
    NSLog(@">>>>>>>>>>>.smalyou:链接服务器的状态发生变化");
    NSString *tips = [NSString stringWithFormat:@"当前%@",(aConnectionState == EMConnectionConnected?@"网络已连接":@"网络未连接")];
    [self showText:tips];
    
}

/**自动登录完成时的回调*/
- (void)autoLoginDidCompleteWithError:(EMError *)aError
{
    NSLog(@">>>>>>>>>>>.smalyou:自动登录完成时的回调");
}



/**当前登录账号在其它设备登录时会接收到此回调*/
- (void)userAccountDidLoginFromOtherDevice
{
    
    //账号在异地登录
    WEAKSELF
    UIAlertController *ac = [UIAlertController alertControllerWithTitle:@"错误" message:@"您的账号在另一台设备上登录，您已经被迫退出！" preferredStyle:UIAlertControllerStyleAlert];
    [ac addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        //清除登录信息
//        [[UserManager shareInstance] doLogout];
        
        //弹出登录控制器
//        UIStoryboard *story = [UIStoryboard storyboardWithName:@"Login" bundle:nil];
//        UIViewController *vc = [story instantiateInitialViewController];
//        [weakSelf presentViewController:vc animated:YES completion:nil];
        
        
    }]];
    
    [self presentViewController:ac animated:YES completion:nil];
    
    
}

/*当前登录账号已经被从服务器端删除时会收到该回调*/
- (void)userAccountDidRemoveFromServer
{
    NSLog(@">>>>>>>>>>>.smalyou:当前账号已经被从服务器端删除");
}

/*服务被禁*/
- (void)userDidForbidByServer
{
    NSLog(@">>>>>>>>>>>.smalyou:服务被禁");
}

#pragma mark - EMChatManagerDelegate
/**收到消息*/
- (void)messagesDidReceive:(NSArray *)aMessages
{
    
    EMMessage *message = aMessages.firstObject;
    EMMessageBody *firstMessageBody = message.body;
    BOOL isSOS = NO;
    switch (firstMessageBody.type) {
        case EMMessageBodyTypeText:
        {
            EMTextMessageBody *textBody = (EMTextMessageBody *)firstMessageBody;
            if ([textBody.text isEqualToString:@"SOS test"]) {
                //SOS 消息
                isSOS = YES;
            }
        }
            break;
        case EMMessageBodyTypeImage:
        {
            EMImageMessageBody *imgMessageBody = (EMImageMessageBody *)firstMessageBody;
            //判断是否是SOS紧急消息
            NSDictionary *ext = message.ext;
            if (ext == nil || ![ext.allKeys containsObject:@"latitude"] || ![ext.allKeys containsObject:@"longitude"] ) {
                isSOS = NO;
            }else{
                isSOS = YES;
                
            }
            
            
        }
            break;
        case EMMessageBodyTypeLocation:
        {
            EMLocationMessageBody *locationBody = (EMLocationMessageBody *)firstMessageBody;
            if ([locationBody.address isEqualToString:@"SOS test"]) {
                //SOS 消息
                isSOS = YES;
            }
        }
            break;
        default:
            break;
    }
    
    //取出消息
    GPMessageItem *item = [[GPMessageItem alloc] initWithMessage:message];
    NSString *title = isSOS?@"You have Emergency SOS message":@"You have a new message";
    title = @"You have a new message";
    switch (item.bodyType) {
        case EMMessageBodyTypeText:
            title = item.text;
            break;
        default:
            break;
    }
    //查询用户名昵称
    NSString *username= isSOS?@"":@"Friend";
    NSArray *profileM = [GPProfileItem selectDBWithHid:message.from];
    if (profileM.count) {
        GPProfileItem *profile = profileM.firstObject;
        username = profile.name;
    }
    
    //播放声音
//    if( [[NSUserDefaults standardUserDefaults] boolForKey:kSettingVoiceStatus]){
        [[GPDeviceManager shareManager] playNewMessageSound];
//    }
    //播放震动
//    if( [[NSUserDefaults standardUserDefaults] boolForKey:kSettingShakeStatus]){
        [[GPDeviceManager shareManager] playVibration];
//    }
    //生成本地通知
//    if(![[NSUserDefaults standardUserDefaults] boolForKey:kSettingPriventMessageStatus]){
    
//        UILocalNotification *noti = [[UILocalNotification alloc] init];
//        if (noti) {
//            //设置推送时间
//            noti.fireDate = [NSDate new];//=now
//            
//            //设置时区
//            noti.timeZone = [NSTimeZone defaultTimeZone];
//            
//            //设置重复间隔
//            noti.repeatInterval = 0;
//            
//            //推送声音
//            noti.soundName = UILocalNotificationDefaultSoundName;
//            
//            //内容
//            noti.alertBody = title;
//            noti.alertTitle = username;
//            
//            //设置userinfo 方便在之后需要撤销的时候使用
//            NSDictionary *infoDic = [NSDictionary dictionaryWithObject:@"name" forKey:@"key"];
//            noti.userInfo = infoDic;
//            
//            //添加推送到uiapplication
//            UIApplication *app = [UIApplication sharedApplication];
//            [app scheduleLocalNotification:noti];
//        }
//    }
}



//#pragma mark - EMCallManagerDelegate
//
///*!
// *  用户A拨打用户B，用户B会收到这个回调
// *
// *  @param aSession  会话实例
// */
//- (void)callDidReceive:(EMCallSession *)aSession
//{
//    
//    NSLog(@"------------------>接收到用户的视频音频请求");
//    
//}





@end
